// component/bloglist/bloglist.js
import { 
  USER_BLOG,
 } from "../../request/api";

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    listData:{
      type: Object,
      observer: function(newVal, oldVal){
        if(newVal.height){
          this.setData({
            listViewData: {
              height: newVal.height,
            }
          });
        }
        if(newVal.userId){
          this.data.userId = newVal.userId;
          if(this.data.dataList.length == 0){
            this.loadMore();
          }
        }
        if(newVal.isMyBlog){
          this.data.isMyBlog = newVal.isMyBlog;
        }
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    dataList:[],
    pageToken: '',
    userId: '',
    isMyBlog: false,
    listViewData: {
      loadStatus: 2,
    },
  },

  lifetimes: {
    ready: function(){
      if(this.data.dataList.length == 0){
        this.loadMore();
      }
    }
  },

  pageLifetimes: {
    // show: function(){
    //   this.loadMore();
    // },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    toDetail: function(e){
      var id = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '/pages/article/detail/detail?id='+id+'&type=3',
      });
    },
    
    refresh: function(){
      // this.setData({
      //   dataList: [],
      //   pageToken: '',
      // });
      this.data.dataList = [];
      this.data.pageToken = '';
      this.loadMore();
    },
    loadMore: function(){
      if(this.data.listViewData.loadStatus == 1){
        return;
      }
      if(!this.data.userId && !this.data.isMyBlog){
        return;
      }
      this.data.listViewData.loadStatus = 1;
      USER_BLOG({'userId': this.data.userId, 'pageToken': this.data.pageToken}).then(res => {
        if(res.data.code == 1){
          var result = res.data.result;
          var list = result.items;
          if(this.data.pageToken){
            list = this.data.dataList.concat(list);
          }
          this.setData({
            dataList: list,
            pageToken: result.nextPageToken,
            listViewData: {
              loadStatus: result.responseCount < result.requestCount? 3 : 2,
            },
          });
        } else {
          this.setLoadStatus(2);
        }
      }).catch(err => {
        this.setLoadStatus(2);
      });
    },
    setLoadStatus: function(status){
      this.setData({
        listViewData: {
          loadStatus: status,
        },
      });
    }
  }
})
